package utils

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
)

// AESEncrypt
// @Author: lee
// @Date: 2022-01-14 10:09:22
// @Description: AES CBC加密
func AESEncrypt(plaintext, key []byte) (ciphertext []byte, err error) {
	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		return nil, err
	}

	blockSize := block.BlockSize()
	plaintext = PKCS7Padding(plaintext, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	ciphertext = make([]byte, len(plaintext))
	blockMode.CryptBlocks(ciphertext, plaintext)

	return ciphertext, nil
}

// AESDecrypt
// @Author: lee
// @Date: 2022-01-14 10:08:50
// @Description: AES CBC解密
func AESDecrypt(ciphertext, key []byte) (plaintext []byte, err error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	plaintext = make([]byte, len(ciphertext))
	blockMode.CryptBlocks(plaintext, ciphertext)
	plaintext = PKCS7UnPadding(plaintext)

	return plaintext, nil
}

// PKCS7Padding
// @Author: lee
// @Date: 2022-01-14 10:07:59
// @Description: 数据长度填充
func PKCS7Padding(cipherText []byte, blockSize int) []byte {
	padding := blockSize - len(cipherText)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(cipherText, padText...)
}

// PKCS7UnPadding
// @Author: lee
// @Date: 2022-01-14 10:06:37
// @Description: 删除填充的数据
func PKCS7UnPadding(plaintext []byte) []byte {
	length := len(plaintext)
	unPadding := int(plaintext[length-1])
	return plaintext[:(length - unPadding)]
}
